package com.studyv3.test.controller.waste;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.studyv3.common.annotation.Log;

import com.studyv3.common.annotation.RepeatSubmit;
import com.studyv3.common.core.controller.BaseController;
import com.studyv3.common.core.domain.AjaxResult;
import com.studyv3.common.core.domain.R;
import com.studyv3.common.core.domain.model.LoginUser;
import com.studyv3.common.core.page.*;
import com.studyv3.common.core.validate.AddGroup;
import com.studyv3.common.enums.BusinessType;
import com.studyv3.common.exception.ServiceException;
import com.studyv3.common.utils.poi.ExcelUtilPlus;
import com.studyv3.framework.lock.DistributedLock;
import com.studyv3.test.constants.LaoBaoConstants;
import com.studyv3.test.domain.ApplyWaste;
import com.studyv3.test.domain.Stock;
import com.studyv3.test.domain.bo.ApplyWasteBo;
import com.studyv3.test.domain.vo.ApplyWasteVo;
import com.studyv3.test.domain.vo.StockApplyWasteVo;
import com.studyv3.test.mapper.StockMapper;
import com.studyv3.test.service.ApplyWasteService;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * _报废申请/审批
 *
 * @author ruoyi
 * @date 2024-05-07
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/applyWaste")
public class ApplyWasteController extends BaseController {

    private final ApplyWasteService iApplyWasteService;
    private final StockMapper stockMapper;


    /**
     * 按商品、批次获取库存列表,按批次分类
     */
    @GetMapping("/bfstocklist")
    public TableDataInfo bfstocklist(Stock stock) {
        startPage();
        // 加入申请人
        stock.setApplicant(getUsername());
        List<StockApplyWasteVo> list = stockMapper.listStockApplyWaste(stock);
        return getDataTable(list);
    }


    /**
     * 按商品、批次获取库存列表,按批次分类
     */
    @GetMapping("/bfstocklistformanager")
    public TableDataInfo bfstocklistformanager(Stock stock) {
        startPage();
        // 加入申请人
        stock.setApplicant(getUsername());
        List<StockApplyWasteVo> list = stockMapper.listStockApplyWasteForManager(stock);
        return getDataTable(list);
    }

    /**
     * 查询_报废申请/审批列表
     */
//    @SaCheckPermission("system:applyWaste:list")
    @GetMapping("/list")
    public TableDataInfoPlus<ApplyWasteVo> list(ApplyWasteBo bo) {
        startPage();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        bo.setApplicant(getUsername());
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(pageDomain.getPageNum());
        pageQuery.setPageSize(pageDomain.getPageSize());
        return iApplyWasteService.queryPageList(bo,pageQuery);
    }

    /**
     * 按商品、批次获取库存列表,按批次分类
     */
    @GetMapping("/listself")
    public TableDataInfoPlus<ApplyWasteVo> listApplyWaste(ApplyWasteBo bo) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(pageDomain.getPageNum());
        pageQuery.setPageSize(pageDomain.getPageSize());

        return iApplyWasteService.queryPageListSelf(bo, pageQuery);
    }


    /**
     * 查询_报废申请/审批列表
     */
//    @SaCheckPermission("system:applyWaste:list")
    @GetMapping("/listformanager")
    public TableDataInfoPlus<ApplyWasteVo> listformanager(ApplyWasteBo bo) {
        startPage();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(pageDomain.getPageNum());
        pageQuery.setPageSize(pageDomain.getPageSize());
        return iApplyWasteService.queryPageList(bo,pageQuery);
    }

    /**
     * 导出_报废申请/审批列表
     */
//    @SaCheckPermission("system:applyWaste:export")
    @PostMapping("/export")
    public void export(ApplyWasteBo bo, HttpServletResponse response) {
        bo.setApplicant(getUsername());
        List<ApplyWasteVo> list = iApplyWasteService.queryList(bo);
        response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + "-applyTake.xlsx");

        ExcelUtilPlus.exportExcel(list, "员工报废申请", ApplyWasteVo.class, response);
    }


    /**
     * 导出_报废申请/审批列表
     */
//    @SaCheckPermission("system:applyWaste:export")
    @Log(title = "_报废申请/审批", businessType = BusinessType.EXPORT)
    @PostMapping("/exportformanager")
    public void exportformanager(ApplyWasteBo bo, HttpServletResponse response) {
        List<ApplyWasteVo> list = iApplyWasteService.queryList(bo);
        ExcelUtilPlus.exportExcel(list, "主管报废审批", ApplyWasteVo.class, response);
    }

    /**
     * 获取_报废申请/审批详细信息
     *
     * @param id 主键
     */
//    @SaCheckPermission("system:applyWaste:query")
    @GetMapping("/{id}")
    public R<ApplyWasteVo> getInfo(@NotNull(message = "主键不能为空")
                                   @PathVariable Long id) {
        return R.ok(iApplyWasteService.queryById(id));
    }

    /**
     * 员工申请提交和修改申请
     */
//    @SaCheckPermission("system:applyWaste:add")
    @Log(title = "_报废申请/审批", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/employeeApply")
    public AjaxResult add(@Validated(AddGroup.class) @RequestBody ApplyWasteBo bo) {
        LoginUser loginUser = getLoginUser();
        bo.setApplicant(loginUser.getUsername());
        if (Long.parseLong(bo.getObjectAmount()) <= 0) {
            throw new ServiceException("报废数量不能小于0");
        }
        return toAjax(iApplyWasteService.employeeApply(bo));
    }

    /**
     * 新增_报废申请/审批
     */
//    @SaCheckPermission("system:applyWaste:add")
    @Log(title = "_报废申请/审批", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/managerHandleApply")
    public AjaxResult managerHandleApply(@Validated(AddGroup.class) @RequestBody ApplyWasteBo bo) {

        return toAjax(iApplyWasteService.managerAdvice(bo));
    }

//    /**
//     * 员工申请提交和修改申请
//     */
////    @SaCheckPermission("system:applyWaste:add")
//    @Log(title = "_报废申请/审批", businessType = BusinessType.INSERT)
//    @RepeatSubmit()
//    @PostMapping("/employeeApply")
//    @Transactional
//    public AjaxResult add(@Validated(AddGroup.class) @RequestBody List<ApplyWasteBo> boList) {
//        LoginUser loginUser = getLoginUser();
//        boList.forEach(bo -> {
//            // 申请人
//            bo.setApplicant(loginUser.getUsername());
//            if (!iApplyWasteService.employeeApply(bo)){
//                throw new ServiceException("报废申请失败");
//            }
//        });
//        return toAjax(true);
//    }
//
//    /**
//     * 新增_报废申请/审批
//     */
////    @SaCheckPermission("system:applyWaste:add")
//    @Log(title = "_报废申请/审批", businessType = BusinessType.INSERT)
//    @RepeatSubmit()
//    @PostMapping("/managerHandleApply")
//    @Transactional
//    public AjaxResult managerHandleApply(@Validated(AddGroup.class) @RequestBody List<ApplyWasteBo> boList) {
//        boList.forEach(bo -> {
//            // 申请人
//            if (!iApplyWasteService.managerAdvice(bo)){
//                throw new ServiceException("报废处理失败");
//            }
//        });
//        return toAjax(true);
//    }


    /**
     * 修改_报废申请/审批
     */
//    @SaCheckPermission("system:applyWaste:edit")
    @Log(title = "_报废申请/审批", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    @Transactional
    public AjaxResult edit(@RequestBody ApplyWasteBo bo) {
        return toAjax(iApplyWasteService.updateByBo(bo));
    }

    /**
     * 删除_报废申请/审批
     *
     * @param ids 主键串
     */
//    @SaCheckPermission("system:applyWaste:remove")
    @Log(title = "_报废申请/审批", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@NotEmpty(message = "主键不能为空")
                             @PathVariable Long[] ids) {
        return toAjax(iApplyWasteService.deleteWithValidByIds(Arrays.asList(ids), true));
    }


    @PostMapping("/withdrawApply/{ids}")
    @Transactional
    public AjaxResult withdrawApply(@PathVariable Long[] ids) {
        // 撤回申请需要保证 批次id 物品id或物品名称 都不为空  还需要applicant 申请人
        if (ObjectUtil.isAllNotEmpty(ids)) {
            iApplyWasteService.handleWithdrawApply(Arrays.asList(ids));
            return toAjax(true);
        } else {
            return AjaxResult.warn("参数不能为空");
        }
    }

//    @PostMapping("/withdrawAdvice/{ids}")
//    @Transactional
//    public AjaxResult withdrawAdvice(@PathVariable Long[] ids){
//        if (ObjectUtil.isAllNotEmpty(ids)) {
//            iApplyWasteService.handleWithdrawAdvice(Arrays.asList(ids));
//            return toAjax(true);
//        } else {
//            return AjaxResult.warn("参数不能为空");
//        }
//    }

    @PostMapping("/countApplyWaste")
    public R<Long> countApplyWaste() {
        Long aLong = 0L;
        LambdaQueryWrapper<ApplyWaste> applyWasteLambdaQueryWrapper = Wrappers.lambdaQuery();
        applyWasteLambdaQueryWrapper.eq(ApplyWaste::getFlag, LaoBaoConstants.BF_APPLY_FLAG);
        aLong = iApplyWasteService.getBaseMapper().selectCount(applyWasteLambdaQueryWrapper);
        return R.ok(aLong);
    }

    @PostMapping("/bfAutoApplyScheduled")
    public R<Void> bfAutoApplyScheduled() {
        iApplyWasteService.bfAutoApplyScheduled();
        return R.ok();
    }

}
